package com.itcs.netty.client;

import com.itcs.box.util.DateUtils;
import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandler.Sharable;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.handler.timeout.IdleStateEvent;
import io.netty.util.ReferenceCountUtil;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import java.nio.charset.Charset;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

/**
 * 
 * @author LiuPeng
 * 
 */
@Sharable
public class NettyClientHandler extends SimpleChannelInboundHandler<ByteBuf> {

	private Log logger = LogFactory.getLog(NettyClientHandler.class);

	public static Map<String, String> resJsonList = new ConcurrentHashMap<>();

	public NettyClientHandler() {

	}

	@Override
	public void userEventTriggered(ChannelHandlerContext ctx, Object evt) throws Exception {
		if (evt instanceof IdleStateEvent) {
//			IdleStateEvent e = (IdleStateEvent) evt;
//			switch (e.state()) {
//			case WRITER_IDLE:
////				BaseMsg pingMsg = new BaseMsg(MsgType.PING);
//				ctx.writeAndFlush("{\"messgeType\": \"1002\",\"data\": {\"deviceId\": \"client_1\",\"status\": \"1\"},\"key\": \"1\"}");
//				logger.info("向服务端心跳测试...");
//				break;
//			default:
//				break;
//			}
		}
	}

	@Override
	protected void channelRead0(ChannelHandlerContext channelHandlerContext, ByteBuf byteBuf) throws Exception {
		String paramJson = getDecode(byteBuf);
		logger.info("收到服务端消息:" + paramJson);
		resJsonList.put(DateUtils.getToday("yyyy-MM-dd HH:mm:ss"), paramJson);
		ReferenceCountUtil.release(byteBuf);
	}

	public String getDecode(ByteBuf byteBuf) {
		String jsonString = byteBuf.toString(Charset.forName("UTF-8")).trim();
		// 测试工具编码为gb2312 如果是测试工具将进行转码
		if (jsonString.contains("lee")) {
			jsonString = byteBuf.toString(Charset.forName("gb2312")).trim();
		}
		return jsonString;
	}
}